'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Search, Plus, Edit, Trash2, Image } from 'lucide-react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';

interface Carousel {
  id: number;
  imageUrl: string | null;
  hyperlink: string | null;
}

export default function CarouselsPage() {
  const [carousels, setCarousels] = useState<Carousel[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [carouselToDelete, setCarouselToDelete] = useState<number | null>(null);
  const [editingCarousel, setEditingCarousel] = useState<Carousel | null>(null);
  const [newCarousel, setNewCarousel] = useState({
    hyperlink: '',
    imageFile: null as File | null
  });
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);

  useEffect(() => {
    fetchCarousels();
  }, []);

  const fetchCarousels = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/carousels');
      
      if (!response.ok) {
        throw new Error('获取轮播图数据失败');
      }
      
      const data = await response.json();
      setCarousels(data.carousels);
    } catch (error) {
      console.error('获取轮播图失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddCarousel = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const formData = new FormData();
      if (newCarousel.imageFile) {
        formData.append('image', newCarousel.imageFile);
      }
      if (newCarousel.hyperlink) {
        formData.append('hyperlink', newCarousel.hyperlink);
      }

      const response = await fetch('/api/carousels', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        throw new Error('添加轮播图失败');
      }

      // 重置表单并刷新数据
      setNewCarousel({ hyperlink: '', imageFile: null });
      setPreviewUrl(null);
      setIsDialogOpen(false);
      fetchCarousels();
    } catch (error) {
      console.error('添加轮播图失败:', error);
    }
  };

  const handleUpdateCarousel = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingCarousel) return;

    try {
      const formData = new FormData();
      if (newCarousel.imageFile) {
        formData.append('image', newCarousel.imageFile);
      }
      if (newCarousel.hyperlink !== undefined) {
        formData.append('hyperlink', newCarousel.hyperlink);
      }

      const response = await fetch(`/api/carousels/${editingCarousel.id}`, {
        method: 'PUT',
        body: formData,
      });

      if (!response.ok) {
        throw new Error('更新轮播图失败');
      }

      // 重置表单并刷新数据
      setNewCarousel({ hyperlink: '', imageFile: null });
      setPreviewUrl(null);
      setEditingCarousel(null);
      setIsDialogOpen(false);
      fetchCarousels();
    } catch (error) {
      console.error('更新轮播图失败:', error);
    }
  };

  const handleDeleteCarousel = async () => {
    if (carouselToDelete === null) return;

    try {
      const response = await fetch(`/api/carousels/${carouselToDelete}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        throw new Error('删除轮播图失败');
      }

      // 刷新数据
      setIsDeleteDialogOpen(false);
      setCarouselToDelete(null);
      fetchCarousels();
    } catch (error) {
      console.error('删除轮播图失败:', error);
    }
  };

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];
      setNewCarousel({ ...newCarousel, imageFile: file });
      
      // 创建预览URL
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreviewUrl(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const openEditDialog = (carousel: Carousel) => {
    setEditingCarousel(carousel);
    setNewCarousel({
      hyperlink: carousel.hyperlink || '',
      imageFile: null
    });
    setPreviewUrl(carousel.imageUrl);
    setIsDialogOpen(true);
  };

  const openAddDialog = () => {
    setEditingCarousel(null);
    setNewCarousel({ hyperlink: '', imageFile: null });
    setPreviewUrl(null);
    setIsDialogOpen(true);
  };

  const filteredCarousels = carousels.filter(carousel => 
    carousel.hyperlink?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    carousel.id.toString().includes(searchTerm)
  );

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">轮播图管理</h1>
          <p className="text-muted-foreground">管理网站首页轮播图</p>
        </div>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-xl font-bold">轮播图列表</CardTitle>
          <div className="flex items-center space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                type="search"
                placeholder="搜索轮播图..."
                className="pl-8 w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
              <DialogTrigger asChild>
                <Button>
                  <Plus className="mr-2 h-4 w-4" />
                  添加轮播图
                </Button>
              </DialogTrigger>
            </Dialog>
          </div>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center items-center h-[400px]">
              <p>加载中...</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>图片预览</TableHead>
                  <TableHead>超链接</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredCarousels.map((carousel) => (
                  <TableRow key={carousel.id}>
                    <TableCell>{carousel.id}</TableCell>
                    <TableCell>
                      {carousel.imageUrl ? (
                        <div className="relative h-16 w-32 overflow-hidden rounded-md border">
                          <img 
                            src={`/api/static/${encodeURIComponent(carousel.imageUrl.replace('D:\\upload\\', ''))}`} 
                            alt="轮播图" 
                            className="h-full w-full object-cover"
                            onError={(e) => {
                              (e.target as HTMLImageElement).src = '/placeholder.jpg';
                              (e.target as HTMLImageElement).alt = '图片加载失败';
                            }}
                          />
                        </div>
                      ) : (
                        <div className="flex h-16 w-32 items-center justify-center rounded-md border bg-muted">
                          <Image className="h-8 w-8 text-muted-foreground" />
                        </div>
                      )}
                    </TableCell>
                    <TableCell>
                      {carousel.hyperlink ? (
                        <a 
                          href={carousel.hyperlink} 
                          target="_blank" 
                          rel="noopener noreferrer"
                          className="text-blue-500 hover:underline truncate block max-w-xs"
                        >
                          {carousel.hyperlink}
                        </a>
                      ) : (
                        <span className="text-muted-foreground">无链接</span>
                      )}
                    </TableCell>
                    <TableCell className="text-right">
                      <Button
                        variant="outline"
                        size="icon"
                        onClick={() => openEditDialog(carousel)}
                        className="mr-2"
                      >
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="outline"
                        size="icon"
                        onClick={() => {
                          setCarouselToDelete(carousel.id);
                          setIsDeleteDialogOpen(true);
                        }}
                        className="text-destructive"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* 添加/编辑轮播图对话框 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editingCarousel ? '编辑轮播图' : '添加新轮播图'}</DialogTitle>
            <DialogDescription>
              {editingCarousel ? '修改轮播图信息' : '请填写以下信息创建新的轮播图'}
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={editingCarousel ? handleUpdateCarousel : handleAddCarousel}>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="hyperlink" className="text-right">
                  超链接
                </Label>
                <Input
                  id="hyperlink"
                  placeholder="请输入轮播图跳转链接"
                  value={newCarousel.hyperlink}
                  onChange={(e) => setNewCarousel({ ...newCarousel, hyperlink: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="image" className="text-right">
                  轮播图
                </Label>
                <div className="col-span-3">
                  <Input
                    id="image"
                    type="file"
                    accept="image/*"
                    onChange={handleImageChange}
                  />
                  {previewUrl && (
                    <div className="mt-2">
                      <p className="text-sm text-muted-foreground mb-1">图片预览:</p>
                      <div className="relative h-40 w-full overflow-hidden rounded-md border">
                        <img 
                          src={previewUrl} 
                          alt="预览图" 
                          className="h-full w-full object-contain"
                        />
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
                取消
              </Button>
              <Button type="submit">{editingCarousel ? '更新' : '创建'}</Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              您确定要删除这个轮播图吗？此操作不可撤销，图片文件将被永久删除。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={handleDeleteCarousel}>删除</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}